package users

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"log"
	"tao-admin/internal/model"
	"tao-admin/utils"
)

type UserService struct {
	UserManager *UserManager
}

func NewUserService() *UserService {
	return &UserService{
		UserManager: &UserManager{},
	}
}

func (service *UserService) GetUserInfos(ctx *gin.Context, condition *SearchUserCondition) ([]model.UserTab, int64, error) {
	//page, _ := strconv.Atoi(ctx.Query("page_no"))
	//count, _ := strconv.Atoi(ctx.Query("count"))
	//condition := &SearchUserCondition{}
	if username, isExist := ctx.GetQuery("username"); isExist == true {
		condition.Username = &username
	}
	if name, isExist := ctx.GetQuery("name"); isExist == true {
		condition.Name = &name
	}
	if password, isExist := ctx.GetQuery("password"); isExist == true {
		condition.Password = &password //加密
	}
	if email, isExist := ctx.GetQuery("email"); isExist == true {
		condition.Email = &email
	}
	if telephone, isExist := ctx.GetQuery("telephone"); isExist == true {
		condition.Telephone = &telephone
	}

	list, total, err := service.UserManager.SearchUserByConditionMng(ctx, condition)
	if err != nil {
		return nil, 0, err
	}
	log.Printf("SearchByConditionMng, list: %v, total: %v", &list, total)
	return list, total, nil
}

func (service *UserService) CreateUserItem(ctx *gin.Context) (err error, msg string) {
	var item model.UserTab
	bodyBytes, err := ioutil.ReadAll(ctx.Request.Body)
	if err != nil {
		return err, "数据解析出错！(Read Request.Body)"
	}
	err = json.Unmarshal(bodyBytes, &item)
	if err != nil {
		return err, "数据解析出错！(Unmarshal)"
	}

	if item.Username == nil || item.Password == nil || item.Email == nil {
		return nil, "存在必填项未填写！"
	}

	timeStamp := utils.GetCurrentTimeStamp()
	item.Ctime = &timeStamp
	item.Mtime = &timeStamp
	var valid int64 = 1
	item.IsValid = &valid
	if item.Role == nil {
		var role int64 = 0
		item.Role = &role
	}

	err = service.UserManager.CreateUserMng(ctx, item)
	if err != nil {
		return err, "插入数据出错！"
	}
	return nil, ""
}

func (service *UserService) UpdateUserItem(ctx *gin.Context) (err error, msg string) {
	var item model.UserTab
	bodyBytes, err := ioutil.ReadAll(ctx.Request.Body)
	if err != nil {
		return err, "数据解析出错！(Read Request.Body)"
	}
	err = json.Unmarshal(bodyBytes, &item)
	if err != nil {
		return err, "数据解析出错！(Unmarshal)"
	}
	if item.Id == nil {
		return nil, "Id必传！"
	}
	err = service.UserManager.UpdateUserMng(ctx, item)
	if err != nil {
		return err, "更新数据出错！"
	}
	return nil, ""
}

func (service *UserService) HandleLogin(item model.UserTab) (err error, msg string) {
	if item.Id == nil {
		return nil, "Id必传！"
	}
	err = service.UserManager.UpdateLoginMng(item)
	if err != nil {
		return err, "更新数据出错！"
	}
	return nil, ""
}
